package cn.ulc.socket.admin.controller;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.ulc.common.constant.enums.AvailableStatus;
import cn.ulc.common.util.Result;
import cn.ulc.socket.admin.model.dto.goods.GoodsTypeListDTO;
import cn.ulc.socket.admin.model.param.goods.GoodsTypeSaveParam;
import cn.ulc.socket.admin.service.goods.GoodsTypeServ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;

@Validated
@RestController
@RequestMapping(value = "/goodsTypes")
public class GoodsTypeCtrl {
    private static final Log log = LogFactory.get();

    @Autowired
    GoodsTypeServ typeServ;

    @GetMapping("/tree/list")
    public Result findTreeList() {
        GoodsTypeListDTO dto = typeServ.findTreeList();
        return Result.success(dto);
    }
    @GetMapping("/water/list")
    public Result findWaterList(String name, AvailableStatus status) {
        GoodsTypeListDTO dto = typeServ.findWaterList(name, status);
        return Result.success(dto);
    }
    @GetMapping("")
    public Result findList(String name, AvailableStatus status) {
        GoodsTypeListDTO dto = typeServ.findList(name, status);
        return Result.success(dto);
    }
    @GetMapping("/{id}")
    public Result findDetail(@PathVariable Long id) {
        return Result.success(typeServ.findDetail(id));
    }

    @PostMapping
    public Result save(@Validated @RequestBody GoodsTypeSaveParam param, BindingResult result){
        if(result.hasErrors()) {
            log.error("新增商品分类详情参数错误",result.getFieldError().getDefaultMessage());
            return Result.fail(result.getFieldError().getDefaultMessage());
        }
        return Result.success(typeServ.save(param),true);
    }
    @PutMapping("/{id}")
    public Result update(@PathVariable("id") Long id, @RequestBody GoodsTypeSaveParam param, BindingResult result){
        if(result.hasErrors()) {
            log.error("保存商品分类详情参数错误",result.getFieldError().getDefaultMessage());
            return Result.fail(result.getFieldError().getDefaultMessage());
        }
        return Result.success(typeServ.update(id,param),true);
    }
    //改变状态
    @PutMapping("/changeStatus/{id}")
    public Result changeStatus(@PathVariable("id") Long id ,AvailableStatus status){
        return Result.success(typeServ.changeStatus(id,status),true);
    }
    //排序
    @PutMapping("/changeSort")
    public Result changeSort(String type,Long id1,Long id2){
        return Result.success(typeServ.changeSort(type,id1,id2),true);
    }
    @DeleteMapping("/{id}")
    public Result deleted(@PathVariable @Min(1) Long id){
        return Result.success(typeServ.deleted(id),true);
    }
}
